<?php

declare(strict_types=1);

namespace App\Traits\Model\Payment;



use App\Model\Orders\Order;
use App\Resource\Orders\OrderResource;
use App\Resource\Payment\PaymentResource;
use Hyperf\Context\Context;
use Hyperf\Database\Model\Relations\BelongsTo;
use function Hyperf\Support\make;
use function Hyperf\Config\config;

trait Payment
{
    /**
     * 设置支付单号
     * @param $value
     */
    public function setNoAttribute($value)
    {
        if (!$value) {
            $value = $this->getNo();
        }
        $this->attributes['no'] = $value;
    }

    /**
     * 关联订单
     * @return BelongsTo
     */
    public function order():BelongsTo
    {
        return $this->belongsTo(Order::class, 'order_no', 'no');
    }

    /**
     * 去退款
     * @param array $input
     * @param string $refundNo
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function goRefund(array $input): array
    {
        $params = (new PaymentResource($this))->toRefundArray($input);

        /** @var \App\Factory\Refund\Factory $factory */
        $factory = make(\App\Factory\Refund\Factory::class);

        if (!in_array($this->code, [
            'safepayMini'
        ])) {
            $config = config("cloud.payment.{$this->code}.{$this->order->shop_id}");
            Context::set('pay_config_array', $config);
        }

        return $factory->{$this->code}($params);
    }
}
